package bancosys.tec.rtm.impl.diagnostician;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import bancosys.tec.rtm.diagnostician.AbstractDiagnostician;
import bancosys.tec.rtm.diagnostician.DiagnosisBean;

/**
 * Diagnosticador que recupera o conteúdo de um recusrso através do classpath.
 * 
 * @author cesar
 */
public class ClassPathResourceContentsDiagnostician extends AbstractDiagnostician {

    private String resourceName;

    /**
     * Construtor.
     * 
     * @param resourceName o nome do recurso.
     */
    public ClassPathResourceContentsDiagnostician(String resourceName) {
        this.resourceName = resourceName;
    }

    /**
     * @return nome.
     */
    public String getName() {
        return "Conteúdo do recurso " + this.resourceName;
    }

    /**
     * {@inheritDoc}
     */
    protected boolean fillDiagnosisBean(DiagnosisBean bean) {
        URL url = this.getClass().getClassLoader().getResource(this.resourceName);
        if (url == null) {
            bean.addDescription("Recurso não encontrado.");
            return false;
        }
        bean.addDescription("Caminho: " + url.getFile());
        bean.addDescription("Conteúdo:");

        try {
            InputStream in = url.openStream();
            InputStreamReader reader = new InputStreamReader(in);
            BufferedReader buf = new BufferedReader(reader);
            String line = buf.readLine();
            while (line != null) {
                bean.addDescription(line);
                line = buf.readLine();
            }
            return true;
        } catch (IOException e) {
            bean.addDescription("Erro recuperando conteúdo." + e.getMessage());
            return false;
        }
    }

}
